package com.itheima.leyou.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.leyou.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {

    @Resource
    UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map<String, Object> login(String username, String password, HttpServletRequest httpServletRequest){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //1、从userService里取出会员信息
        resultMap = userService.getUser(username, password);

        //2、如果没有会员信息，则写入会员信息
        if (!(Boolean) resultMap.get("result")){
            resultMap = userService.insertUser(username, password);

            //3、如果会员信息写入失败则返回失败信息
            if (!(Boolean) resultMap.get("result")){
                resultMap.put("result", false);
                resultMap.put("msg", "");
                return resultMap;
            }
        }

        //4、写入session
        HttpSession httpSession = httpServletRequest.getSession();
        String userObj = JSON.toJSONString(resultMap);
        httpSession.setAttribute("user", userObj);
        return resultMap;
    }
}
